/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yaps.petstore.service;



import com.yaps.petex.transport.Delivery;
import com.yaps.petex.transport.DeliveryPlace;
import com.yaps.petstore.dao.OrderDAO;
import com.yaps.petstore.dto.CartItem;
import com.yaps.petstore.entity.customer.Address;
import com.yaps.petstore.entity.customer.Customer;
import com.yaps.petstore.entity.order.CreditCard;
import com.yaps.petstore.entity.order.Order;
import com.yaps.petstore.entity.order.OrderLine;
import com.yaps.petstore.exception.ValidationException;
import com.yaps.petstore.util.Constants;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;


/**
 *
 * @author belhassine
 */

@Scope("singleton")
@Service("OrderService")
public class OrderService implements IOrderService{

    private final String cname = this.getClass().getName();
    private Logger logger = Logger.getLogger(Constants.LOGGER_STATELESS);
    
    @Autowired
    OrderDAO orderDAO;
    
   @Autowired
    private Delivery delivery;
    
    @Override
    public Order createOrder(Customer customer, Address deliveryAddress, CreditCard creditCard, List<CartItem> cartItems) {
       final String mname = "createOrder";
        logger.entering(cname, mname, cartItems.size());

        // On s'assure de la validité des paramètres
        if (cartItems == null || cartItems.size() == 0)
            throw new ValidationException("Shopping cart is empty");

        // Creation du bon de commande
        Order order = new Order(customer, deliveryAddress, creditCard);

        // A partir du panier electronique on crée les lignes du bon de commande
        List<OrderLine> orderLines = new ArrayList<OrderLine>();

        for (CartItem cartItem : cartItems) {
            orderLines.add(new OrderLine(cartItem.getQuantity(), cartItem.getItem()));
        }
        order.setOrderLines(orderLines);
        
        System.out.println(orderLines.get(0));        
        // L'objet est persisté en base de données
        order = orderDAO.createOrder(order);
        
                      
        // publishOrder(order);
        notifyTransporter(order);

        logger.exiting(cname, mname, order);
        return order;
    }

    @Override
    public Order findOrder(Long orderId) {
       return orderDAO.findOrder(orderId);
    }

    @Override
    public void deleteOrder(Order order) {
        final String mname = "deleteOrder";
        logger.entering(cname, mname, order);

        // On s'assure de la validité des paramètres
        if (order == null)
            throw new ValidationException("Order object is null");

        // On supprime l'objet de la base de données
        orderDAO.deleteOrder(order);

        logger.exiting(cname, mname);
    }

    @Override
    public List<Order> findOrders() {
         final String mname = "findOrders";
        logger.entering(cname, mname);

        
        List<Order> orders;

        orders = orderDAO.findOrders();

        logger.exiting(cname, mname, orders.size());
        return orders;
    }
    
  /*      private void publishOrder(Order order) {
        String mname = "publishOrder";
        logger.entering(cname, mname, order);
        Session session = null;
        try {
            // Ouvre une session JMS
            // Les arguments utilisés ici sont ceux recommandés
            // lorsque que la transaction est gérée par le containeur (container-managed)
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

            // Create a producer
            MessageProducer producer = session.createProducer(destinationOrder);

            // Create a message
            ObjectMessage objectMessage = session.createObjectMessage();
            // Add in header the distinct categories
            Set<Category> categories = Order.getDistinctCategories(order);
            for (Category c : categories) {
                objectMessage.setBooleanProperty(c.getName(), true);
            }
            objectMessage.setObject(order);

            producer.send(objectMessage);
            logger.finest("Message sent in " + destinationOrder);
        } catch (JMSException e) {
            logger.throwing(cname, mname, e);
            // rollback the undergoing transaction if error occured
            throw new EJBException(e);
        } finally {
            try {
                session.close();
            } catch (JMSException e) {
                logger.warning("Exception occured while closing javax.jms.Session: " + e.getMessage());
                throw new EJBException(e);
            }
        }
        logger.exiting(cname, mname);
    }

    */

    private void notifyTransporter(Order order) {
        String mname = "notifyTransporter";
        logger.entering(cname, mname, order);

        DeliveryPlace from = new DeliveryPlace();
        DeliveryPlace to = new DeliveryPlace();

        from.setContact(Constants.COMPANY_NAME);
        from.setStreet(Constants.COMPANY_STREET);
        from.setCity(Constants.COMPANY_CITY);
        from.setState(Constants.COMPANY_STATE);
        from.setZipcode(Constants.COMPANY_ZIPCODE);
        from.setCountry(Constants.COMPANY_COUNTRY);

        to.setContact(order.getCustomer().getLastname());
        to.setStreet(order.getDeliveryAddress().getStreet1());
        to.setCity(order.getDeliveryAddress().getCity());
        to.setState(order.getDeliveryAddress().getState());
        to.setZipcode(order.getDeliveryAddress().getZipcode());
        to.setCountry(order.getDeliveryAddress().getCountry());


        delivery.deliverItems(from, to, order.getId().toString());
        logger.info("Delivery Service has been called. ");

        logger.exiting(cname, mname);
    }
    
    
    
}
